package controller

import (
	"apitestAfterGo/common"
	"apitestAfterGo/domain"
	"apitestAfterGo/dto"
	"apitestAfterGo/service"
	"apitestAfterGo/utils"
	"github.com/kataras/iris/v12/context"
	"github.com/kataras/iris/v12/mvc"
)

type TaskController struct {
}

func (t *TaskController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("POST", "/getAllTaskByPage", "GetAllTaskByPage")
	b.Handle("DELETE", "/deleteTaskById/{id:int}", "DeleteTaskById")
	b.Handle("POST", "/addTask", "AddTask")
	b.Handle("PUT", "/modifyTaskById", "ModifyTaskById")
	b.Handle("GET", "/getTaskById/{id:int}", "GetTaskById")
	b.Handle("POST", "/runTask", "RunTask")
}

func (t *TaskController) GetAllTaskByPage(dto dto.TaskInputDtoByPage) common.Result {
	tasks, count := service.TaskServiceImpl.GetAllTaskByPage(dto)
	pages := utils.GetPages(count, dto.PageSize)
	page := domain.Page{
		Pages:   pages,
		Total:   count,
		Current: dto.Current,
		Size:    dto.PageSize,
		Records: tasks,
	}
	return utils.Success(page, "获取任务成功")
}

func (t *TaskController) DeleteTaskById(id int) common.Result {
	status := service.TaskServiceImpl.DeleteTaskById(id)
	return utils.Success(status, "删除当前任务成功")
}

func (t *TaskController) AddTask(context *context.Context, task domain.Task) common.Result {
	username := utils.GetJwtParameter(context, "username").(string)
	task.UpdateBy = username
	task.CreateBy = username
	status := service.TaskServiceImpl.AddTask(task)
	return utils.Success(status, "添加任务成功")
}

func (t *TaskController) ModifyTaskById(context *context.Context, task domain.Task) common.Result {
	username := utils.GetJwtParameter(context, "username").(string)
	task.UpdateBy = username
	newTask := service.TaskServiceImpl.ModifyTaskById(task)
	return utils.Success(newTask, "更新任务成功")
}

func (t *TaskController) GetTaskById(id int) common.Result {
	newTask := service.TaskServiceImpl.GetTaskById(id)
	return utils.Success(newTask, "获取任务详情成功")
}

func (t *TaskController) RunTask(context *context.Context, task domain.TaskRecord) common.Result {
	username := utils.GetJwtParameter(context, "username").(string)
	task.UpdateBy = username
	task.CreateBy = username
	submitTask := service.TaskRecordServiceImpl.SubmitTask(task)
	return utils.Success(submitTask, "提交任务成功")
}
